package com.ims.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ims.dao.MenuMapper;
import com.ims.pojo.Menu;
import com.ims.service.MenuService;
import com.ims.service.PrivilegeService;
import com.ims.service.UserRoleCorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: zk
 * @date: 2022/9/3 16:07
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private UserRoleCorService userRoleCorService;

    @Autowired
    private PrivilegeService privilegeService;

    @Override
    public List<Menu> selectMenuList() {
        QueryWrapper<Menu> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", 0);
        List<Menu> menuList = menuMapper.selectList(wrapper);
        for (Menu menu : menuList) {
            wrapper = new QueryWrapper<>();
            wrapper.eq("parent_id", menu.getMenuId());
            menu.setChildren(menuMapper.selectList(wrapper));
        }
        return menuList;
    }

    /**
     * 依据用户id 取得对应的 menu_id list
     * @param userId
     * @return
     */
    @Override
    public List<Menu> selectMenuListById(Integer userId) {
        ArrayList<Menu> menus = new ArrayList<>(); //最终返回的结果
        List<Integer> roleIdList = userRoleCorService.findRoleIdByUserId(userId);
        List<List<Integer>> menuIdList = privilegeService.FindMenuIdByRoleId(roleIdList);//获得userId对应的父菜单和子菜单列表
        List<Integer> parentList = menuIdList.get(0);
        List<Integer> childrenList = menuIdList.get(1);
        // 若一级菜单为1，则其对应的二级菜单范围是 [100, 200)
        for (Integer pId : parentList) {
            Menu parentMenu = menuMapper.selectById(pId);
            LambdaQueryWrapper<Menu> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Menu::getParentId, pId);
            wrapper.in(Menu::getMenuId, childrenList);
            List<Menu> children = menuMapper.selectList(wrapper);
            parentMenu.setChildren(children);
            menus.add(parentMenu);
        }
        return menus;
    }
}